package com.example.myapplicationwork;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class HomeActivity extends AppCompatActivity implements
        HomeFragment.OnInterestUpdatedListener,
        ProfileFragment.OnProfileInteractionListener {

    private static final String TAG = "HomeActivity";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_CURRENT_INTEREST = "current_interest";
    private static final String KEY_SELECTED_NAV = "selected_nav"; // 保存导航选中状态
    private static final int NAV_HOME = 0;
    private static final int NAV_PROFILE = 1;

    private String username;
    private String currentInterest = "未选择";
    private int selectedNavItem = NAV_HOME; // 默认选中首页
    private Button btnNavHome;
    private Button btnNavProfile;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");

        // 允许屏幕跟随传感器旋转
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

        // 恢复旋转前的状态
        if (savedInstanceState != null) {
            restoreState(savedInstanceState);
        } else {
            // 首次创建时获取登录信息
            initDataFromIntent();
        }

        setContentView(R.layout.activity_home);
        initViews();
        initFragmentManager();

        // 旋转后不重复创建Fragment，直接恢复状态
        if (savedInstanceState == null) {
            switchToSelectedFragment();
        } else {
            updateNavigationUI(); // 恢复导航选中状态
        }
    }

    // 从Intent初始化数据（首次登录）
    private void initDataFromIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            username = intent.getStringExtra("username");
        }
    }

    // 从savedInstanceState恢复数据（旋转后）
    private void restoreState(Bundle savedInstanceState) {
        username = savedInstanceState.getString(KEY_USERNAME);
        currentInterest = savedInstanceState.getString(KEY_CURRENT_INTEREST, "未选择");
        selectedNavItem = savedInstanceState.getInt(KEY_SELECTED_NAV, NAV_HOME);
    }

    // 初始化视图和导航事件
    private void initViews() {
        btnNavHome = findViewById(R.id.btn_nav_home);
        btnNavProfile = findViewById(R.id.btn_nav_profile);

        btnNavHome.setOnClickListener(v -> switchNav(NAV_HOME));
        btnNavProfile.setOnClickListener(v -> switchNav(NAV_PROFILE));
    }

    // 初始化Fragment管理器
    private void initFragmentManager() {
        fragmentManager = getSupportFragmentManager();
        // 防止旋转时Fragment重叠（移除旧的Fragment事务）
        fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    // 切换导航项
    private void switchNav(int navItem) {
        selectedNavItem = navItem;
        updateNavigationUI();
        switchToSelectedFragment();
    }

    // 更新导航按钮选中状态
    private void updateNavigationUI() {
        btnNavHome.setSelected(selectedNavItem == NAV_HOME);
        btnNavProfile.setSelected(selectedNavItem == NAV_PROFILE);
    }

    // 切换到选中的Fragment
    private void switchToSelectedFragment() {
        if (selectedNavItem == NAV_HOME) {
            switchToFragment(HomeFragment.newInstance(currentInterest), "home_fragment");
        } else {
            switchToFragment(ProfileFragment.newInstance(username, currentInterest), "profile_fragment");
        }
    }

    // 通用Fragment切换方法（确保不重叠）
    private void switchToFragment(Fragment targetFragment, String tag) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        // 隐藏所有已添加的Fragment
        for (Fragment fragment : fragmentManager.getFragments()) {
            if (fragment != null && fragment.isAdded()) {
                transaction.hide(fragment);
            }
        }

        // 显示目标Fragment（已存在则直接显示，否则添加）
        Fragment existingFragment = fragmentManager.findFragmentByTag(tag);
        if (existingFragment != null) {
            transaction.show(existingFragment);
        } else {
            transaction.add(R.id.fragment_container, targetFragment, tag);
        }

        transaction.commit();
    }

    // 保存状态（旋转前调用）
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_USERNAME, username);
        outState.putString(KEY_CURRENT_INTEREST, currentInterest);
        outState.putInt(KEY_SELECTED_NAV, selectedNavItem);
        Log.d(TAG, "状态已保存: " + currentInterest + ", 导航项: " + selectedNavItem);
    }

    // 兴趣更新回调（同步到两个Fragment）
    @Override
    public void onInterestUpdated(String interest) {
        currentInterest = interest;

        // 更新首页Fragment
        HomeFragment homeFragment = (HomeFragment) fragmentManager.findFragmentByTag("home_fragment");
        if (homeFragment != null) {
            homeFragment.updateInterest(interest);
        }

        // 更新我的Fragment
        ProfileFragment profileFragment = (ProfileFragment) fragmentManager.findFragmentByTag("profile_fragment");
        if (profileFragment != null) {
            profileFragment.updateInterest(interest);
        }
    }

    // 退出登录回调
    @Override
    public void onLogout() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish(); // 退出登录后关闭当前页面
    }

    // 选择兴趣回调
    @Override
    public void onSelectInterest() {
        Intent intent = new Intent(this, InterestSelectActivity.class);
        startActivityForResult(intent, 1001);
    }

    // 处理兴趣选择返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            String interests = data.getStringExtra("interests");
            if (interests != null && !interests.isEmpty()) {
                onInterestUpdated(interests);
            }
        }
    }

    // 生命周期日志（便于调试）
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG, "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "onNewIntent");
        if (intent != null) {
            username = intent.getStringExtra("username");
        }
    }
}
